package controller

import (
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"khao.fun/shizhan/common"
	"khao.fun/shizhan/dto"
	"khao.fun/shizhan/model"
	"khao.fun/shizhan/response"
	"khao.fun/shizhan/service"
	"net/http"
)

var DB *gorm.DB


// @Summary 注册用户
// @Description 注册用户
// @Tags User_profile
// @Accept mpfd
// @Produce json
// @Param user_name formData string true "用户名"
// @Param user_email formData string true "用户电子邮箱"
// @Param user_pwd formData string true "用户密码"
// @Param user_code formData string true "验证码"
// @Success 200 {string} string "{"msg": "注册成功"}"
// @Failure 422 {string} string "{"msg": "无效邮箱号","密码不能少于6位","邮箱已存在","验证码错误"}"
// @Failure 500 {string} string "{"msg": "加密失败"}"
// @Router /auth/register [post]
func User_profile_Resgister(ctx *gin.Context) {
	DB = common.GetDB()
	name := ctx.PostForm("user_name")
	email := ctx.PostForm("user_email")
	//telephone := ctx.PostForm("user_tel")
	password := ctx.PostForm("user_pwd")
	code := ctx.PostForm("user_code")


	if common.VerifyEmailFormat(email) == false{
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "无效邮箱号")
		return
	}

	//if len(telephone) != 11 {
	//	response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机位必须11位")
	//	return
	//}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}
	if len(name) == 0 {
		//name =common.RandString(10)
		name = common.RandaomString(10)
	}

	//创建用户
	hasePassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 500, nil, "加密失败")
		return
	}
	if isEmailExist(email) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "邮箱已存在")
		return
	}
	icode :=common.Code("activate",email)
	if code!=icode || icode=="" {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "验证码错误")
		return
	}
	//if isTelephoneExist(telephone) {
	//	response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号已存在")
	//	return
	//}

	newUser := model.User_profile{
		User_name:  name,
		User_email: email,
		//User_tel:   telephone,
		User_pwd:   string(hasePassword),

	}
	service.User_profile_Create(&newUser)
	newUser_detail := model.User_detail{
		User_id: newUser.User_id,
	}
	service.User_detail_Create(&newUser_detail)
	response.Success(ctx, nil, "注册成功")

}



// @Summary 用户登录
// @Description 用户登录
// @Tags User_profile
// @Accept mpfd
// @Produce json
// @Param user_email formData string true "用户电子邮箱"
// @Param user_pwd formData string true "用户密码"
// @Success 200 {string} string "{"msg": "登录成功"}"
// @Failure 422 {string} string "{"msg": "用户不存在"，"系统错误"}"
// @Failure 400 {string} string "{"msg": "密码错误"}"
// @Router /auth/login [post]
func User_profile_Login(ctx *gin.Context) {
	//telephone := ctx.PostForm("user_tel")
	email := ctx.PostForm("user_email")
	password := ctx.PostForm("user_pwd")
	var user model.User_profile
	service.User_profile_Login(&user, email)
	if user.User_id == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}

	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.User_pwd), []byte(password)); err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "密码错误")
		return
	}

	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "系统错误")
		return
	}

	response.Success(ctx, gin.H{"token": token}, "登录成功")
}


// @Summary 获取用户信息
// @Description 获取用户信息
// @Tags User_profile
// @Accept mpfd
// @Produce json
// @Router /auth/info [get]
func User_profile_Info(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	ctx.JSON(http.StatusUnprocessableEntity, gin.H{
		"user": dto.Dto_User_profile(user.(model.User_profile)),
	})

}

func isEmailExist(email string) bool {
	var user model.User_profile
	service.User_CheckemailInfo(&user, email)
	return user.User_id != 0
}

//func isTelephoneExist(telephone string) bool {
//	var user model.User_profile
//	service.User_ChecktelInfo(&user, telephone)
//	return user.User_id != 0
//}


// @Summary 删除用户信息
// @Description 删除用户信息
// @Tags User_profile
// @Accept mpfd
// @Produce json
// @Param user_id formData string true "用户id"
// @Success 200 {string} string "{"msg": "删除成功"}"
// @Failure 400 {string} string "{"msg": "error"}"
// @Router /auth/info [delete]
func User_profile_Delete(ctx *gin.Context) {
	id := ctx.PostForm("user_id")
	err:=service.User_profile_Delete(id)
	if err!=nil{
		response.Fail(ctx, http.StatusBadRequest, nil, err.Error())
	}else {
		response.Success(ctx, nil, "删除成功")
	}
}


// @Summary 向用户发送验证码
// @Description 向用户发送验证码
// @Tags User_profile
// @Accept mpfd
// @Produce json
// @Param user_email formData string true "用户email"
// @Success 200 {string} string "{"msg": "已发送验证码到您的邮箱,100秒内有效"}"
// @Failure 422 {string} string "{"msg": "无效邮箱号","邮箱已存在","请等待一百秒后再重新发送验证码"}"
// @Router /auth/code [post]
func User_profile_Code(ctx *gin.Context) {
	email := ctx.PostForm("user_email")
	if common.VerifyEmailFormat(email) == false{
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "无效邮箱号")
		return
	}
	if isEmailExist(email) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "邮箱已存在")
		return
	}
	code:=common.CodeChange("activate",email)
	if code=="-1"{
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "请等待一百秒后再重新发送验证码")
		return
	}
	common.Sentemail(email,"激活验证码",code)
	response.Success(ctx, nil, "已发送验证码到您的邮箱,100秒内有效")
}



// @Summary 用户升级
// @Description 用户升级
// @Tags User_profile
// @Accept mpfd
// @Produce json
// @Param user_id formData string true "用户id"
// @Param user_identity formData string true "用户等级"
// @Success 200 {string} string "{"msg": "OK"}"
// @Failure 422 {string} string "{"msg": "user cant be empty","error"}"
// @Router /auth/upgrade [put]
func User_profile_Upgrade(ctx *gin.Context) {

	user_id := ctx.PostForm("user_id")
	user_identity := ctx.PostForm("user_identity")
	var data model.User_profile
	data.User_id = common.AtoUin32(user_id)
	data.User_identity = common.AtoUin8(user_identity)
	if user_id == "" {
		response.Fail(ctx, http.StatusBadRequest, nil, "user cant be empty")
		return
	}
	err := service.User_profile_Upgrade(&data)
	if err != nil {
		response.Fail(ctx, http.StatusBadRequest, nil, err.Error())
	} else {
		response.Success(ctx, nil, "OK")
	}
}

//21.10.14更新 swagger